package zsy.test.properties.i18n;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * properties文件值按照key排序
 * 
 * @author zhangshuaiyin
 * @date 2022/5/18 12:00
 */
public class I18nSort {
    public static final String IGNORE_FLAG = "#";
    public static final String SPLITTER = "=";
    public static final String FILE_PATH = "C:\\Users\\59498\\Downloads\\JAVA-emm-strategy\\en_US_messages.properties";
    public static final String FILE_PATH2 = "C:\\Users\\59498\\Downloads\\JAVA-emm-strategy\\en_US_validation.properties";
    public static final String FILE_PATH3 = "C:\\Users\\59498\\Downloads\\JAVA-emm-strategy\\messages_en_US.properties";
    public static final String FILE_PATH4 = "C:\\Users\\59498\\Downloads\\JAVA-emm-strategy\\validation_en_US.properties";

    public static void main(String[] args) throws Exception {
        BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH));
        File f = new File("b-out.properties");
        FileOutputStream fop = new FileOutputStream(f);
        // 构建FileOutputStream对象,文件不存在会自动新建
        OutputStreamWriter writer = new OutputStreamWriter(fop, StandardCharsets.UTF_8);
        // 构建OutputStreamWriter对象,参数可以指定编码,默认为操作系统默认编码,windows上是gbk
        String line = null;
        List<I18nDTO> list = new ArrayList<>();
        while ((line = reader.readLine()) != null) {
            if (line.startsWith(IGNORE_FLAG)) {
                list.add(new I18nDTO().setId(line));
            } else {
                String[] split = line.split(SPLITTER);
                list.add(new I18nDTO().setId(split[0]).setMessage(split[1]));
            }
        }
        Collections.sort(list);
        list.forEach(item -> {
            try {
                writer.write(item.toString());
                writer.write("\n");
            } catch (IOException e) {
                e.printStackTrace();
            }
        });


        writer.close();
        // 关闭写入流,同时会把缓冲区内容写入文件,所以上面的注释掉

        fop.close();
    }
}
